/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: PersonInfoActivity.java
 * @Package com.jiyi.activity.zone
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2017-6-15 下午1:43:31
 * @version V1.0
 */
package com.jiyi.activity.zone;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.easeui.EaseConstant;
import com.jiyi.activity.SinglePicActivity;
import com.jiyi.activity.main.JiYouXiuFaBuActivity;
import com.jiyi.bean.zone.JiYouXiuBean;
import com.jiyi.bean.zone.RxPersonInfoBean;
import com.jiyi.bean.zone.RxUploadBean;
import com.jiyi.bean.zone.Topic;
import com.jiyi.bean.zone.UserInfoBean;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.easemob.view.EasemobChatActivity;
import com.jiyi.event.JiYouXiuListEvent;
import com.jiyi.event.UserInfoEvent;
import com.jiyi.exception.SampleProgressObserver;
import com.jiyi.inteface.WebApi;
import com.jiyi.retrofit.HttpMethods;
import com.shizhefei.view.indicator.FragmentListPageAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorFragmentPagerAdapter;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.GlideUtil;
import com.swift.utils.PhotoUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * @ClassName: PersonInfoActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-15 下午1:43:31
 */
public class PersonInfoActivity extends SinglePicActivity  {

    @BindView(R.id.tvBack)
    TextView tvBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;

    @BindView(R.id.id_stickynavlayout_indicator)
    ScrollIndicatorView mIndicator;
    @BindView(R.id.id_stickynavlayout_viewpager)
    ViewPager mViewPager;
    @BindView(R.id.ivLogo)
    ImageView ivLogo;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvSexAge)
    TextView tvSexAge;
    @BindView(R.id.tvSign)
    TextView tvSign;
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.ivMessage)
    ImageView ivMessage;

    IndicatorViewPager indicatorViewPager;
    private LayoutInflater inflate;

    private String[] names = {"吉友秀", "话题", "活动"};
    // 用户ID
    private String id;
    private List<ZoneHuoDongBean> huoDongDatas = new ArrayList<ZoneHuoDongBean>();
    private List<JiYouXiuBean> jiYouXiuDatas = new ArrayList<JiYouXiuBean>();
    private List<Topic> topicDatas = new ArrayList<Topic>();

    private final int CROP_SMALL_PICTURE = 4;

    // 进度条
    Dialog dialog;
    // 是否好友
    Boolean is_friend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        ButterKnife.bind(this);
        getIntentData();
        getPersonInfo();
        setTop();
        EventBus.getDefault().register(this);
        // initIndicator();
    }


    @Subscribe
    public void onJiYouXiuListEvent(JiYouXiuListEvent jiYouXiuListEvent) {
        int type = jiYouXiuListEvent.type;
        switch (type) {
            case JiYouXiuListEvent.PERSON_JIYOUXIU_FRAGMENT:
                getPersonInfo();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        hideDialog(dialog);
        super.onDestroy();
    }

    /**
     * @author: HYM
     * @Title: getPersonInfo
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-7-4
     */
    private void getPersonInfo() {

        HttpMethods.getInstance().getUserInfo(UserInfoUtil.getCurrentUserAccessToken(), id)
                .subscribe(new SampleProgressObserver<RxPersonInfoBean>(this) {
                    @Override
                    public void onNext(RxPersonInfoBean rxPersonInfoBean) {
                        Log.e("onNext ", rxPersonInfoBean.toString());
                        final UserInfoBean userInfoBean = rxPersonInfoBean.getUserInfo();
                        if (null != userInfoBean) {
                            GlideUtil.load(PersonInfoActivity.this,
                                    userInfoBean.getHead_path(),
                                    ivLogo);

                            // 查看自己就隐藏掉加好友、私信
                            if (id.equals(UserInfoUtil.getCurrentUserId() + "")) {
                                ivMessage.setVisibility(View.GONE);
                                tvAdd.setVisibility(View.GONE);
                            } else {
                                if (userInfoBean.getIs_friend() == 0) {
                                    tvAdd.setText("+ 好友");
                                    is_friend = false;
                                    ivMessage.setVisibility(View.GONE);
                                    tvAdd.setVisibility(View.VISIBLE);
                                } else {
                                    tvAdd.setText("已是好友");
                                    tvAdd.setVisibility(View.VISIBLE);
                                    is_friend = true;
                                    ivMessage
                                            .setVisibility(View.VISIBLE);
                                    ivMessage
                                            .setOnClickListener(new View.OnClickListener() {

                                                @Override
                                                public void onClick(
                                                        View v) {
                                                    Intent intent2 = new Intent(
                                                            v.getContext(),
                                                            EasemobChatActivity.class);
                                                    intent2.putExtra(
                                                            ClouldChatType.INTENT_USER_PIC,
                                                            userInfoBean
                                                                    .getHead_path());
                                                    intent2.putExtra(
                                                            "id",
                                                            userInfoBean
                                                                    .getId());
                                                    intent2.putExtra(
                                                            "name",
                                                            userInfoBean
                                                                    .getName());
                                                    intent2.putExtra(
                                                            "easemobgid",
                                                            userInfoBean
                                                                    .getAccount());
                                                    intent2.putExtra(
                                                            ClouldChatType.INTENT_Group_Id,
                                                            "");
                                                    intent2.putExtra(
                                                            "easeMobChatType",
                                                            EaseConstant.CHATTYPE_SINGLE);
                                                    startActivity(intent2);

                                                }
                                            });
                                }
                            }


                            tvCompany.setText(userInfoBean
                                    .getBranchname());
                            tvName.setText(userInfoBean.getName());
                            tvSign.setText(userInfoBean.getMotto());
                            tvSexAge.setText(userInfoBean.getSex());

                        }
                        huoDongDatas = rxPersonInfoBean
                                .getUserActList();
                        jiYouXiuDatas = rxPersonInfoBean
                                .getShowFriend();
                        topicDatas = rxPersonInfoBean.getTopicList();
                        initIndicator();
                    }
                });


//		if (TextUtils.isEmpty(id)) {
//			ToastUtil.getInstances().showMsg("无效的ID");
//			finish();
//			return;
//		}
//		Map<String, String> params = new HashMap<String, String>();
//		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
//		params.put("id", id);
//
//		dialog = showDialog(dialog);
//		VolleyRequest.StringRequestPost(this, WebApi.ZONE_PERSONAL_INFO, "",
//				params, new StringInterface(this) {
//
//					@Override
//					public void stringSuccess(String result) {
//						try {
//							JSONObject obj = new JSONObject(result);
//							String status = obj.getString("status");
//							String info = obj.getString("info");
//							if (status.equals("200")) {
//								PersonInfoJson temp = new Gson().fromJson(
//										result, PersonInfoJson.class);
//								if (temp == null || temp.getData() == null) {
//									ToastUtil.getInstances().showMsg("无效的用户");
//									finish();
//									return;
//								} else {
//									final UserInfoBean userInfoBean = temp
//											.getData().getUserInfo();
//									if (null != userInfoBean) {
//										GlideUtil.load(PersonInfoActivity.this,
//												userInfoBean.getHead_path(),
//												ivLogo);
//
//										// 查看自己就隐藏掉加好友、私信
//										if (id.equals(UserInfoUtil.getCurrentUserId() + "")) {
//											ivMessage.setVisibility(View.GONE);
//											tvAdd.setVisibility(View.GONE);
//										}
//										else {
//											if (userInfoBean.getIs_friend() == 0) {
//												tvAdd.setText("+ 好友");
//												is_friend = false;
//												ivMessage.setVisibility(View.GONE);
//												tvAdd.setVisibility(View.VISIBLE);
//											} else {
//												tvAdd.setText("已是好友");
//												tvAdd.setVisibility(View.VISIBLE);
//												is_friend = true;
//												ivMessage
//														.setVisibility(View.VISIBLE);
//												ivMessage
//														.setOnClickListener(new OnClickListener() {
//
//															@Override
//															public void onClick(
//																	View v) {
//																Intent intent2 = new Intent(
//																		v.getContext(),
//																		EasemobChatActivity.class);
//																intent2.putExtra(
//																		ClouldChatType.INTENT_USER_PIC,
//																		userInfoBean
//																				.getHead_path());
//																intent2.putExtra(
//																		"id",
//																		userInfoBean
//																				.getId());
//																intent2.putExtra(
//																		"name",
//																		userInfoBean
//																				.getName());
//																intent2.putExtra(
//																		"easemobgid",
//																		userInfoBean
//																				.getAccount());
//																intent2.putExtra(
//																		ClouldChatType.INTENT_Group_Id,
//																		"");
//																intent2.putExtra(
//																		"easeMobChatType",
//																		EaseConstant.CHATTYPE_SINGLE);
//																startActivity(intent2);
//
//															}
//														});
//											}
//										}
//
//
//										tvCompany.setText(userInfoBean
//												.getBranchname());
//										tvName.setText(userInfoBean.getName());
//										tvSign.setText(userInfoBean.getMotto());
//										tvSexAge.setText(userInfoBean.getSex());
//
//									}
//									huoDongDatas = temp.getData()
//											.getUserActList();
//									jiYouXiuDatas = temp.getData()
//											.getShowFriend();
//									topicDatas = temp.getData().getTopicList();
//									initIndicator();
//								}
//
//							} else {
//								ToastUtil.getInstances().showMsg(info);
//							}
//						} catch (JSONException e) {
//							e.printStackTrace();
//						} finally {
//							hideDialog(dialog);
//						}
//					}
//
//					@Override
//					public void stringError(VolleyError error) {
//						hideDialog(dialog);
//						ToastUtil.getInstances().showMsg(R.string.err_http_response);
//					}
//				});
    }

    /**
     * @author: HYM
     * @Title: getIntentData
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-7-4
     */
    private void getIntentData() {
        id = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(id)) {
            ToastUtil.getInstances().showMsg("无效的ID");
            finish();
            return;
        }
    }

    /**
     * @author: HYM
     * @Title: setTop
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-6-15
     */
    private void setTop() {
        tvBack.setText("");
        tvTitle.setText("个人资料");
        if (UserInfoUtil.getCurrentUserId() == Integer.parseInt(id)) {
            Drawable searchDraw = getResources().getDrawable(
                    R.mipmap.icon_edit);
            searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),
                    searchDraw.getMinimumHeight());
            tvSearch.setCompoundDrawables(searchDraw, null, null, null);
            tvSearch.setText("发布秀");
        } else {
            tvSearch.setVisibility(View.GONE);
        }

    }

    /**
     * @author: HYM
     * @Title: initIndicator
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-6-15
     */
    private void initIndicator() {
        inflate = LayoutInflater.from(this);
        mIndicator.setScrollBar(new ColorBar(this, Color.parseColor("#16B0F4"),
                5));

        // 设置滚动监听
        int selectColorId = R.color.tab_top_on;
        int unSelectColorId = R.color.tab_top;
        int selectSizeId = R.dimen.tab_text_select;
        int unSelectSizeId = R.dimen.tab_text_noselect;

        mIndicator.setOnTransitionListener(new OnTransitionTextListener()
                .setValueFromRes(this, selectColorId, unSelectColorId,
                        selectSizeId, unSelectSizeId));

        indicatorViewPager = new IndicatorViewPager(mIndicator, mViewPager);
        indicatorViewPager
                .setAdapter(new MyAdapter(getSupportFragmentManager()));
        indicatorViewPager.setPageOffscreenLimit(2);
    }

    private class MyAdapter extends IndicatorFragmentPagerAdapter {

        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public int getCount() {
            return names.length;
        }

        @Override
        public View getViewForTab(int position, View convertView,
                                  ViewGroup container) {
            if (convertView == null) {
                convertView = inflate.inflate(R.layout.tab_top, container,
                        false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(names[position % names.length]);
            textView.setPadding(20, 0, 20, 0);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {
            Log.d("getFragmentForPage    ", "getFragmentForPage" + position);
            Fragment curFragment = null;
            Bundle bundle = null;
            switch (position) {
                case 0:
                    // 吉友秀
                    curFragment = new PersonInfoXiuFragment();
                    bundle = new Bundle();
                    bundle.putString("datas", new Gson().toJson(jiYouXiuDatas));
                    curFragment.setArguments(bundle);
                    break;
                case 1:
                    // 话题
                    curFragment = new PersonInfoTopicFragment();
                    bundle = new Bundle();
                    bundle.putString("datas", new Gson().toJson(topicDatas));
                    curFragment.setArguments(bundle);
                    break;
                case 2:
                    // 活动
                    curFragment = new PersonInfoHuoDongFragment();
                    bundle = new Bundle();
                    bundle.putString("id", id);
                    bundle.putString("datas", new Gson().toJson(huoDongDatas));
                    curFragment.setArguments(bundle);
                    break;
                default:
                    break;
            }

            return curFragment;
        }

        @Override
        public int getItemPosition(Object object) {
            return FragmentListPageAdapter.POSITION_NONE;
        }

    }

    ;

    @OnClick({R.id.tvBack, R.id.ivLogo, R.id.tvAdd, R.id.tvSearch,
            R.id.ivMessage})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.tvBack:
                finish();
                break;
            case R.id.ivLogo:
                if (UserInfoUtil.isCurrentUser(Integer.parseInt(id))) {
                    mPickPopView.showPopWindow();
                }
                break;
            case R.id.tvAdd:
                if (!is_friend) {
                    addHaoYou(id);
                }

                break;
            case R.id.tvSearch:
                intent = new Intent(this, JiYouXiuFaBuActivity.class);
                startActivity(intent);
                break;
            case R.id.ivMessage:

                break;
            default:
                break;
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case CAMARE_CODE:
                    startPhotoZoom(mCameraUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
//                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                        String filePath = CameraUtils.getImageAbsolutePath(this, mCameraUri);
                        File imgFile = null;
                        if (!TextUtils.isEmpty(filePath)) {
                            imgFile = new File(filePath);
                        }

                        if (imgFile == null)
                            return;

                        // 创建 RequestBody，用于封装 请求RequestBody
                        RequestBody requestFile =
                                RequestBody.create(MediaType.parse("multipart/form-data"), imgFile);

// MultipartBody.Part is used to send also the actual file name
                        MultipartBody.Part file =
                                MultipartBody.Part.createFormData("head_path", imgFile.getName(), requestFile);

                        MultipartBody.Part token =
                                MultipartBody.Part.createFormData(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

                        HttpMethods.getInstance().uploadPic(token, file)
                                .subscribe(new SampleProgressObserver<RxUploadBean>(this) {
                                    @Override
                                    public void onNext(RxUploadBean emptyResult) {
                                        ToastUtil.getInstances().showMsg("上传成功");
                                        String url = emptyResult.getUrl();
                                        Log.e(TAG, "url: "+url);
                                        GlideUtil.load(PersonInfoActivity.this,url,ivLogo);
                                        if (!TextUtils.isEmpty(url)) {
                                            ZoneHaoYouBean zoneHaoYouBean = new ZoneHaoYouBean();
                                            zoneHaoYouBean.setHead_path(url);
                                            EventBus.getDefault().postSticky(
                                                    new UserInfoEvent(zoneHaoYouBean));
                                            UserInfoUtil.setCurrentUserLogo(url);
                                        }
                                    }
                                });
                    }
                    break;
            }
        }

    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        mCameraUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            photo = PhotoUtils.toRoundBitmap(photo, mCameraUri); // 这个时候的图片已经被处理成圆形的了
            ivLogo.setImageBitmap(photo);
            uploadPic(photo);
        }
    }

    private void uploadPic(Bitmap bitmap) {
        String imagePath = PhotoUtils.savePhoto(bitmap, PhotoUtils.USER_LOGO,
                String.valueOf(System.currentTimeMillis()));
        Log.e("imagePath", imagePath + "");
        if (imagePath != null) {
            // 拿着imagePath上传了
            String webApi = WebApi.ZONE_LOGO_UPLOAD;
            Map<String, String> params = new HashMap<String, String>();
            params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

            PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
            postForm.params(params);
            if (!TextUtils.isEmpty(imagePath)) {
                File file = new File(imagePath);
                postForm.addFile("head_path", "user_logo.jpg", file);
            }

            dialog = showDialog(dialog);
            postForm.build().execute(new StringCallback() {

                @Override
                public void onError(Call arg0, Exception exception, int arg2) {
                    // 删除临时头像
                    PhotoUtils.RecursionDeleteFile(new File(
                            PhotoUtils.USER_LOGO));
                    hideDialog(dialog);
                    ToastUtil.getInstances().showMsg(exception.getMessage());
                }

                @Override
                public void onResponse(String result, int arg1) {
                    try {
                        JSONObject obj = new JSONObject(result);
                        String status = obj.getString("status");
                        String info = obj.getString("info");
                        if (status.equals("200")) {
                            ToastUtil.getInstances().showMsg(info);
                            String data = obj.getString("data");
                            JSONObject dataJson = new JSONObject(data);
                            String url = dataJson.getString("url");
                            if (!TextUtils.isEmpty(url)) {
                                ZoneHaoYouBean zoneHaoYouBean = new ZoneHaoYouBean();
                                zoneHaoYouBean.setHead_path(url);
                                EventBus.getDefault().postSticky(
                                        new UserInfoEvent(zoneHaoYouBean));
                                UserInfoUtil.setCurrentUserLogo(url);
                            }
                        } else if (status.equals("404") && info.contains("尚未登录")) {
                            ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
                            //清除环信登录
                            UserHelp.getInstance().clearUser(AppBase.Context, true);
                            return;
                        } else {
                            ToastUtil.getInstances().showMsg(info);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {
                        // 删除临时头像
                        PhotoUtils.RecursionDeleteFile(new File(
                                PhotoUtils.USER_LOGO));
                        hideDialog(dialog);
                    }
                }
            });
        }

    }

    void addHaoYou(String id) {
        if (TextUtils.isEmpty(id)) {
            ToastUtil.getInstances().showMsg("无效的ID");
            finish();
            return;
        }

        HttpMethods.getInstance().addFriend(UserInfoUtil.getCurrentUserAccessToken(), id)
                .subscribe(new SampleProgressObserver<Object>(this) {
                });


//        Map<String, String> params = new HashMap<String, String>();
//        params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
//        params.put("id", id);
//
//        VolleyRequest.StringRequestPost(this, WebApi.ZONE_HAOYOU_ADD, "",
//                params, new StringInterface(this) {
//
//                    @Override
//                    public void stringSuccess(String result) {
//                        try {
//                            JSONObject obj = new JSONObject(result);
//                            String status = obj.getString("status");
//                            String info = obj.getString("info");
//                            if (status.equals("200")) {
//                                ToastUtil.getInstances().showMsg(info);
//                            } else {
//                                ToastUtil.getInstances().showMsg(info);
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        } finally {
//                        }
//                    }
//
//                    @Override
//                    public void stringError(VolleyError error) {
//                        ToastUtil.getInstances().showMsg(R.string.err_http_response);
//                    }
//                });
    }

}
